﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kelper.Controllers;
using System.Text;
using Kelper.ViewModels;

namespace Kelper.Infrastructure.Helpers
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString ActionButton(this HtmlHelper helper,
            string text, string action, string controller)
        {
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            TagBuilder form = new TagBuilder("form");
            form.Attributes.Add("method", "post");
            form.Attributes.Add("action", url.Action(action, controller));
            form.AddCssClass("action-button");

            TagBuilder submit = new TagBuilder("input");
            submit.Attributes.Add("type", "submit");
            submit.Attributes.Add("value", text);

            TagBuilder span = new TagBuilder("span");
            span.InnerHtml = submit.ToString();
            form.InnerHtml = span.ToString();

            return new MvcHtmlString(form.ToString());
        }

        public static MvcHtmlString Linebreaks(this HtmlHelper helper, string text)
        {
            string encoded = helper.Encode(text);
            return new MvcHtmlString(encoded.Replace("\n", "<br />"));
        }

        public static MvcHtmlString PageLinks(this HtmlHelper helper,
            int numPages, int currentPage, Func<int, string> pageUrl)
        {
            if (numPages <= 1)
                return new MvcHtmlString("");

            TagBuilder pageLinks = new TagBuilder("div");
            pageLinks.AddCssClass("paging");

            StringBuilder result = new StringBuilder();
            for (int i = 1; i <= numPages; i++)
            {
                TagBuilder tag = new TagBuilder("a");
                tag.MergeAttribute("href", pageUrl(i));
                tag.InnerHtml = i.ToString();
                if (i == currentPage)
                    tag.AddCssClass("current");
                result.Append(tag.ToString());
            }

            pageLinks.InnerHtml = result.ToString();
            return MvcHtmlString.Create(pageLinks.ToString());
        }
    }
}